import request from './request'

/**
 * 教学任务相关接口
 */
export const teachingMissionApi = {
  /**
   * 获取所有教学任务
   */
  getAllTeachingMissions(params = {}) {
    return request({
      url: '/api/teaching-missions',
      method: 'get',
      params
    }).then(response => {
      return response;
    })
  },

  /**
   * 获取所有教学任务（列表形式，用于下拉选择等场景）
   */
  getAllTeachingMissionsList() {
    return request({
      url: '/api/teaching-missions/list',
      method: 'get'
    })
  },

  /**
   * 根据ID获取教学任务
   * @param {number} id 教学任务ID
   */
  getTeachingMissionById(id) {
    return request({
      url: `/api/teaching-missions/${id}`,
      method: 'get'
    })
  },

  /**
   * 创建教学任务
   * @param {Object} teachingMission 教学任务信息
   */
  createTeachingMission(teachingMission) {
    return request({
      url: '/api/teaching-missions',
      method: 'post',
      data: teachingMission
    })
  },

  /**
   * 更新教学任务
   * @param {number} id 教学任务ID
   * @param {Object} teachingMission 教学任务信息
   */
  updateTeachingMission(id, teachingMission) {
    return request({
      url: `/api/teaching-missions/${id}`,
      method: 'put',
      data: teachingMission
    })
  },

  /**
   * 删除教学任务
   * @param {number} id 教学任务ID
   */
  deleteTeachingMission(id) {
    return request({
      url: `/api/teaching-missions/${id}`,
      method: 'delete'
    })
  },

  /**
   * 批量导入教学任务
   * @param {FormData} formData 包含Excel文件的表单数据
   */
  importTeachingMissions(formData) {
    return request({
      url: '/api/teaching-missions/import',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  /**
   * 下载教学任务导入模板
   */
  downloadTemplate() {
    return request({
      method: 'get',
      url: '/api/teaching-missions/template/download',
      responseType: 'blob'
    }).then(response => {
      // 对于 blob 响应，response 现在是完整的 response 对象
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'teaching_mission_import_template.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    }).catch(error => {
      console.error('下载模板失败:', error)
      throw error
    })
  },

  /**
   * 向教学任务添加学生
   * @param {number} teachingMissionId 教学任务ID
   * @param {Array<number>} studentIds 学生ID数组
   */
  addStudentsToTeachingMission(teachingMissionId, studentIds) {
    return request({
      url: `/api/teaching-missions/${teachingMissionId}/students`,
      method: 'post',
      data: studentIds
    })
  },

  /**
   * 获取教学任务的学生列表
   * @param {number} teachingMissionId 教学任务ID
   */
  getTeachingMissionStudents(teachingMissionId) {
    return request({
      url: `/api/teaching-missions/${teachingMissionId}/students`,
      method: 'get'
    })
  },

  /**
   * 从教学任务中移除学生
   * @param {number} teachingMissionId 教学任务ID
   * @param {number} studentId 学生ID
   */
  removeStudentFromTeachingMission(teachingMissionId, studentId) {
    return request({
      url: `/api/teaching-missions/${teachingMissionId}/students/${studentId}`,
      method: 'delete'
    })
  },

  /**
   * 清空教学任务的所有学员
   * @param {number} teachingMissionId 教学任务ID
   */
  clearTeachingMissionStudents(teachingMissionId) {
    return request({
      url: `/api/teaching-missions/${teachingMissionId}/students`,
      method: 'delete'
    })
  },

  /**
   * 根据学期ID获取教学任务（前端过滤）
   * @param {number} termId 学期ID
   */
  getTeachingMissionsByTerm(termId) {
    return this.getAllTeachingMissions().then(missions => {
      // 确保返回的是有效的数组
      const allMissions = Array.isArray(missions) ? missions : [];
      
      // 如果没有提供termId，返回所有教学任务
      if (!termId) return allMissions;
      
      // 将所有类型都转为字符串进行比较，避免类型不一致问题
      const termIdStr = String(termId);
      
      // 在前端过滤出与指定学期匹配的教学任务
      const filteredMissions = allMissions.filter(mission => {
        // 直接使用mission.termId (扁平结构)，或者尝试从term对象中获取 (嵌套结构)
        let missionTermId = mission.termId !== undefined ? mission.termId : 
                           (mission.term && mission.term.id ? mission.term.id : undefined);
        
        if (missionTermId === undefined || missionTermId === null) {
          return false;
        }
        
        // 统一转为字符串比较
        const missionTermIdStr = String(missionTermId);
        const termMatched = missionTermIdStr === termIdStr;
        
        return termMatched;
      });
      
      return filteredMissions;
    });
  },
  
  /**
   * 获取我的教学任务（当前登录教师）
   * @param {Object} params 查询参数
   * @returns {Promise} 教学任务分页数据
   */
  getMyTeachingMissions(params = {}) {
    return request({
      url: '/api/teaching-missions/my',
      method: 'get',
      params
    }).then(response => {
      return response || { content: [], totalElements: 0 };
    }).catch(error => {
      throw error;
    });
  },

  /**
   * 获取教学任务的学员列表（包含成绩信息）
   * @param {number} missionId 教学任务ID
   * @returns {Promise} 学员列表
   */
  getTeachingMissionStudentsWithScores(missionId) {
    return request({
      url: `/api/teaching-missions/${missionId}/students-with-scores`,
      method: 'get'
    }).then(response => {
      return response.data || response || [];
    }).catch(error => {
      throw error;
    });
  },

  /**
   * 导入学员成绩
   * @param {FormData} formData 包含文件和教学任务ID的表单数据
   * @returns {Promise} 导入结果
   */
  importStudentScores(formData) {
    return request({
      url: '/api/scores/part/import',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(response => {
      return response;
    }).catch(error => {
      throw error;
    });
  },

  /**
   * 导出学员成绩
   * @param {number} missionId 教学任务ID
   * @returns {Promise} 导出文件
   */
  exportStudentScores(missionId) {
    return request({
      url: `/api/teaching-missions/${missionId}/export-scores`,
      method: 'get',
      responseType: 'blob'
    }).then(response => {
      // 创建下载链接
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `教学任务_${missionId}_学员成绩.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      return response;
    }).catch(error => {
      throw error;
    });
  },

  /**
   * 获取教学任务的教师详情和排序信息
   * @param {number} missionId 教学任务ID
   * @returns {Promise} 教师排序信息列表
   */
  getTeachingMissionTeachers(missionId) {
    return request({
      url: `/api/teaching-missions/${missionId}/teachers`,
      method: 'get'
    }).then(response => {
      return response || [];
    }).catch(error => {
      throw error;
    });
  },

  /**
   * 获取教学任务的教师列表
   * @param {number} missionId 教学任务ID
   * @returns {Promise} 教师列表
   */
  getTeachingMissionTeachers(missionId) {
    return request({
      url: `/api/teaching-missions/${missionId}/teachers`,
      method: 'get'
    }).then(response => {
      return response;
    }).catch(error => {
      throw error;
    });
  },

  /**
   * 更新教学任务中教师的排序
   * @param {number} missionId 教学任务ID
   * @param {Array<number>} teacherIds 教师ID列表
   * @param {Array<number>} orders 排序位置列表
   * @param {Array<boolean>} primaryFlags 主要教师标记列表
   * @returns {Promise} 更新结果
   */
  reorderTeachers(missionId, teacherIds, orders, primaryFlags) {
    return request({
      url: `/api/teaching-missions/${missionId}/teachers/reorder`,
      method: 'put',
      data: {
        teacherIds,
        orders,
        primaryFlags
      }
    }).then(response => {
      return response;
    }).catch(error => {
      throw error;
    });
  },

  // 关联和解除关联功能已删除
}

/**
 * 根据教师ID获取教学任务
 * @param {number} teacherId 教师ID
 * @returns {Promise} 教学任务列表
 */
export const getTeachingMissionsByTeacherId = async (teacherId) => {
  try {
    const response = await request({
      url: `/api/teaching-missions/teacher/${teacherId}`,
      method: 'get'
    });
    
    return response || [];
  } catch (error) {
    throw error;
  }
};

/**
 * 根据教师ID获取课程（按课程分组的教学任务）
 * @param {number} teacherId 教师ID
 * @returns {Promise} 课程列表
 */
export const getTeacherCourses = async (teacherId) => {
  try {
    const response = await request({
      url: `/api/teaching-missions/teacher/${teacherId}/courses`,
      method: 'get'
    });
    
    return response || [];
  } catch (error) {
    throw error;
  }
};

/**
 * 获取我的教学任务（当前登录教师）
 * @param {Object} params 查询参数
 * @returns {Promise} 教学任务分页数据
 */
export const getMyTeachingMissions = async (params = {}) => {
  return teachingMissionApi.getMyTeachingMissions(params);
};

/**
 * 获取教学任务的学员列表（包含成绩信息）
 * @param {number} missionId 教学任务ID
 * @returns {Promise} 学员列表
 */
export const getTeachingMissionStudents = async (missionId) => {
  return teachingMissionApi.getTeachingMissionStudentsWithScores(missionId);
};

/**
 * 导入学员成绩
 * @param {FormData} formData 包含文件和教学任务ID的表单数据
 * @returns {Promise} 导入结果
 */
export const importStudentScores = async (formData) => {
  return teachingMissionApi.importStudentScores(formData);
};

/**
 * 导出学员成绩
 * @param {number} missionId 教学任务ID
 * @returns {Promise} 导出文件
 */
export const exportStudentScores = async (missionId) => {
  return teachingMissionApi.exportStudentScores(missionId);
};

/**
 * 根据课程ID和学期ID获取教学任务
 * @param {Object} params 查询参数
 * @param {number} params.courseId 课程ID
 * @param {number} params.termId 学期ID
 * @returns {Promise} 教学任务列表
 */
export const getTeachingMissionsByCourseAndTerm = async (params) => {
  try {
    const response = await request({
      url: '/api/teaching-missions/by-course-term',
      method: 'get',
      params
    });
    
    return response.data || response || [];
  } catch (error) {
    throw error;
  }
};
